package com.sqfw.project.wpReport.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.sqfw.common.utils.StringUtils;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.system.mapper.SysUserMapper;
import com.sqfw.project.wp.domain.SysCode;
import com.sqfw.project.wp.domain.WpBackInfo;
import com.sqfw.project.wp.domain.WpHandleLog;
import com.sqfw.project.wp.domain.WpVisitInfo;
import com.sqfw.project.wp.mapper.*;
import com.sqfw.project.wpReport.domain.WpInfoDetail;
import com.sqfw.project.wpReport.domain.dto.VisitCountDTO;
import com.sqfw.project.wpReport.mapper.WpInfoDetailMapper;
import com.sqfw.project.zj.domain.ZjRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sqfw.project.wpReport.domain.WpInfoSatis;
import com.sqfw.project.wpReport.service.IWpInfoSatisService;

/**
 * 市民满意度统计Service业务层处理
 *
 * @author lx
 * @date 2023-07-21
 */
@Service
public class WpInfoSatisServiceImpl implements IWpInfoSatisService
{
    @Autowired
    private WpHandleLogMapper wpHandleLogMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private WpVisitInfoMapper wpVisitInfoMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private WpInfoDetailMapper wpInfoDetailMapper;

    @Autowired
    private WpBackInfoMapper wpBackInfoMapper;

    //三级承办单位顶级 pid  与数据库数据对应  三级承办单位
    private static final Long sysDeptPid = 1L;

    @Override
    public List<WpInfoSatis> getWpInfoSatisList(WpInfoSatis wpInfoSatis) {

        //承办单位id集合
        List<Long> deptList = new ArrayList<>();
        if (StringUtils.isNotEmpty(wpInfoSatis.getMainUnitAll())){
            List<String> mainUnitAll = wpInfoSatis.getMainUnitAll();
            for (String mainUnit : mainUnitAll) {

                String[] split = mainUnit.split(",");
                if (split.length>1){
                    if (!deptList.contains(Long.valueOf(split[1]))){
                        deptList.add(Long.valueOf(split[1]));
                    }

                }else if (split.length==1){
                    List<SysDept> depts = sysDeptMapper.selectChildrenDeptById(Long.valueOf(split[0]));
                    for (SysDept dept : depts) {
                        if (!deptList.contains(dept.getDeptId())){
                            deptList.add(dept.getDeptId());
                        }
                    }
                }
            }
        }else {
            //获取三级承办单位下面的  中心  部门  处室  区县

            List<SysDept> sysDepts = sysDeptMapper.selectChildrenDeptById(sysDeptPid);
            List<Long> parentIds = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            //获取所有承办单位集合

            List<SysDept> sysDeptList = sysDeptMapper.selectDeptListByParentIds(parentIds);
            List<Long> deptIdList = sysDeptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
            deptList.addAll(deptIdList);
        }

        //获取三级承办部门id集合
        List<String> deptLevel2s = deptList.stream()
                .map(String::valueOf)
                .collect(Collectors.toList());
        wpInfoSatis.setDeptLevel2s(deptLevel2s);
        //分配承办单位工单数
        WpHandleLog wpHandleLogDept = new WpHandleLog();
        wpHandleLogDept.setDeptLevel2s(deptLevel2s);
        //使用流转时间或者回访时间
        if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
            wpHandleLogDept.setBegainTime(wpInfoSatis.getVisitBeginTime());
            wpHandleLogDept.setEndTime(wpInfoSatis.getVisitEndTime());
        }else{
            wpHandleLogDept.setBegainTime(wpInfoSatis.getBegainTime());
            wpHandleLogDept.setEndTime(wpInfoSatis.getEndTime());
        }
        wpHandleLogDept.setNextState("承办单位处理");
        List<WpHandleLog> wpHandleLogList =  wpHandleLogMapper.selectWpidListByDeptId(wpHandleLogDept);
        List<WpInfoSatis> wpInfoSatisList = new ArrayList<>();

        //回访
        WpVisitInfo visitInfo = new WpVisitInfo();
        //使用回访时间或者使用流转时间内的工单
        if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
            visitInfo.setBegainTime(wpInfoSatis.getVisitBeginTime());
            visitInfo.setEndTime(wpInfoSatis.getVisitEndTime());
        }
        for (Long deptIdLong : deptList) {
            String deptId = deptIdLong.toString();
            WpInfoSatis wpInfoSatisCon = new WpInfoSatis();
            List<WpHandleLog> handleLogs = wpHandleLogList.stream()
                    .filter(handleLog -> (deptId).equals(handleLog.getNextDepartment1()))
                    .collect(Collectors.toList());
            if (handleLogs.size()==0){
                continue;
            }
            SysDept sysDept = sysDeptMapper.selectDeptById(deptIdLong);
            wpInfoSatisCon.setDeptLevel2Name(sysDept.getDeptName());
            wpInfoSatisCon.setDeptLevel2(deptId);
            //派单总数---受理总数
            Set<String> wpInfoCountWpids = handleLogs.stream()
                    .map(WpHandleLog::getWpid)
                    .collect(Collectors.toSet());

            //TODO
            WpBackInfo wpBackInfo = new WpBackInfo();
//            wpBackInfo.setBegainTime(wpInfoSatis.getBegainTime());
//            wpBackInfo.setEndTime(wpInfoSatis.getEndTime());
            //使用流转时间或者回访时间
            if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
                wpBackInfo.setBegainTime(wpInfoSatis.getVisitBeginTime());
                wpBackInfo.setEndTime(wpInfoSatis.getVisitEndTime());
            }else{
                wpBackInfo.setBegainTime(wpInfoSatis.getBegainTime());
                wpBackInfo.setEndTime(wpInfoSatis.getEndTime());
            }
            wpBackInfo.setDeptLevel2(String.valueOf(sysDept.getDeptId()));
            wpBackInfo.setState("审核人收回工单");
            wpBackInfo.setNextState("审核人处理");
            List<String> recoverCountWpids = wpBackInfoMapper.selectRecoverCountWpids(wpBackInfo);

            //总量
            List<String> wpidsNew = new ArrayList<>();
            if (recoverCountWpids.size()>0){
                for (String recoverCountWpid : recoverCountWpids) {
                    WpHandleLog wpHandleLog = new WpHandleLog();
                    wpHandleLog.setWpid(recoverCountWpid);
//                    wpHandleLog.setBegainTime(wpInfoSatis.getBegainTime());
//                    wpHandleLog.setEndTime(wpInfoSatis.getEndTime());
                    //使用流转时间或者回访时间
                    if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
                        wpHandleLog.setBegainTime(wpInfoSatis.getVisitBeginTime());
                        wpHandleLog.setEndTime(wpInfoSatis.getVisitEndTime());
                    }else{
                        wpHandleLog.setBegainTime(wpInfoSatis.getBegainTime());
                        wpHandleLog.setEndTime(wpInfoSatis.getEndTime());
                    }
                    List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogListByWpidAndTime(wpHandleLog);
                    WpHandleLog wpHandleLog1 = wpHandleLogs.stream().filter(dto -> "承办单位处理".equals(dto.getNextState()))
                            .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);

                    WpHandleLog wpHandleLog2 = wpHandleLogs.stream().filter(dto -> "审核人收回工单".equals(dto.getLastState()))
                            .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
                    if (wpHandleLog1!=null&&wpHandleLog2!=null&&wpHandleLog2.getUpdateTime().compareTo(wpHandleLog1.getUpdateTime())>0){
                        wpidsNew.add(recoverCountWpid);
                    }
                    if (wpHandleLog1!=null&&wpHandleLog2!=null&&wpHandleLog2.getUpdateTime().compareTo(wpHandleLog1.getUpdateTime())<0&&StringUtils.isNotEmpty(wpHandleLog1.getNextDepartment1())
                            &&!wpHandleLog1.getNextDepartment1().equals(sysDept.getDeptId().toString())){
                        wpidsNew.add(recoverCountWpid);
                    }
                }
            }

            if (wpidsNew.size()>0){
                wpInfoCountWpids.removeAll(wpidsNew);
            }




            //流转数
            wpInfoSatisCon.setAcceptedCount(wpInfoCountWpids.size());

            visitInfo.setDeptLevel2(deptId);
            if(wpInfoSatis.getVisitBeginTime()==null || wpInfoSatis.getVisitEndTime()==null){
                //流转工单编号集合
                visitInfo.setWpIdsByFlowTime(wpInfoCountWpids);
            }

            //满意数
            visitInfo.setIssatisfied("满意");
            List<String> satisCount;
            if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
                satisCount =  wpVisitInfoMapper.selectDistentVisitWpid(visitInfo);
            }else{
                satisCount =wpVisitInfoMapper.selectVisitByFlowTime(visitInfo);
            }


            //不满意数
            visitInfo.setIssatisfied("不满意");
            List<String> unSatisCount;
            if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
                unSatisCount =  wpVisitInfoMapper.selectDistentVisitWpid(visitInfo);
            }else{
                unSatisCount =  wpVisitInfoMapper.selectVisitByFlowTime(visitInfo);
            }


            //一般数
            visitInfo.setIssatisfied("一般");
            List<String> kindCount;
            if(wpInfoSatis.getVisitBeginTime()!=null && wpInfoSatis.getVisitEndTime()!=null){
                kindCount =  wpVisitInfoMapper.selectDistentVisitWpid(visitInfo);
            }else{
                kindCount =  wpVisitInfoMapper.selectVisitByFlowTime(visitInfo);
            }



            wpInfoSatisCon.setSatisCount(satisCount.size());

            wpInfoSatisCon.setKindCount(kindCount.size());

            wpInfoSatisCon.setUnsatisCount(unSatisCount.size());
            //回访成功总数
            int satisTotal = satisCount.size()+kindCount.size()+unSatisCount.size();

            wpInfoSatisCon.setVisitSuccessCount(satisTotal);

            String satisRate = getSatisRate(satisTotal, satisCount.size(), kindCount.size());
            wpInfoSatisCon.setSatisRate(satisRate+"%");
            wpInfoSatisList.add(wpInfoSatisCon);

        }



        return wpInfoSatisList;
    }

    @Override
    public List<WpInfoDetail> getUnSatisWpInfoList(WpInfoDetail detailCon) {
        //增加流转时间逻辑
        WpHandleLog wpHandleLogDept = new WpHandleLog();
        List<String> deptLevel2s = new ArrayList<>();
        deptLevel2s.add(detailCon.getDeptLevel2());
        wpHandleLogDept.setDeptLevel2s(deptLevel2s);
        //使用流转时间或者回访时间
        if(detailCon.getVisitBeginTime()!=null && detailCon.getVisitEndTime()!=null){
            wpHandleLogDept.setBegainTime(detailCon.getVisitBeginTime());
            wpHandleLogDept.setEndTime(detailCon.getVisitEndTime());
        }else{
            wpHandleLogDept.setBegainTime(detailCon.getBegainTime());
            wpHandleLogDept.setEndTime(detailCon.getEndTime());
        }
        wpHandleLogDept.setNextState("承办单位处理");
        List<WpHandleLog> wpHandleLogList =  wpHandleLogMapper.selectWpidListByDeptId(wpHandleLogDept);
        //派单总数---受理总数
        Set<String> wpInfoCountWpids = wpHandleLogList.stream()
                .map(WpHandleLog::getWpid)
                .collect(Collectors.toSet());
        //TODO
        WpBackInfo wpBackInfo = new WpBackInfo();
//        wpBackInfo.setBegainTime(wpInfoSatis.getBegainTime());
//        wpBackInfo.setEndTime(wpInfoSatis.getEndTime());
        //使用流转时间或者回访时间
        if(detailCon.getVisitBeginTime()!=null && detailCon.getVisitEndTime()!=null){
            wpBackInfo.setBegainTime(detailCon.getVisitBeginTime());
            wpBackInfo.setEndTime(detailCon.getVisitEndTime());
        }else{
            wpBackInfo.setBegainTime(detailCon.getBegainTime());
            wpBackInfo.setEndTime(detailCon.getEndTime());
        }
        wpBackInfo.setDeptLevel2(detailCon.getDeptLevel2());
        wpBackInfo.setState("审核人收回工单");
        wpBackInfo.setNextState("审核人处理");
        List<String> recoverCountWpids = wpBackInfoMapper.selectRecoverCountWpids(wpBackInfo);

        //总量
        List<String> wpidsNew = new ArrayList<>();
        if (recoverCountWpids.size()>0){
            for (String recoverCountWpid : recoverCountWpids) {
                WpHandleLog wpHandleLog = new WpHandleLog();
                wpHandleLog.setWpid(recoverCountWpid);
//                wpHandleLog.setBegainTime(wpInfoSatis.getBegainTime());
//                wpHandleLog.setEndTime(wpInfoSatis.getEndTime());
                //使用流转时间或者回访时间
                if(detailCon.getVisitBeginTime()!=null && detailCon.getVisitEndTime()!=null){
                    wpHandleLog.setBegainTime(detailCon.getVisitBeginTime());
                    wpHandleLog.setEndTime(detailCon.getVisitEndTime());
                }else{
                    wpHandleLog.setBegainTime(detailCon.getBegainTime());
                    wpHandleLog.setEndTime(detailCon.getEndTime());
                }
                List<WpHandleLog> wpHandleLogs = wpHandleLogMapper.selectWpHandleLogListByWpidAndTime(wpHandleLog);
                WpHandleLog wpHandleLog1 = wpHandleLogs.stream().filter(dto -> "承办单位处理".equals(dto.getNextState()))
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);

                WpHandleLog wpHandleLog2 = wpHandleLogs.stream().filter(dto -> "审核人收回工单".equals(dto.getLastState()))
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime)).orElse(null);
                if (wpHandleLog1!=null&&wpHandleLog2!=null&&wpHandleLog2.getUpdateTime().compareTo(wpHandleLog1.getUpdateTime())>0){
                    wpidsNew.add(recoverCountWpid);
                }
                if (wpHandleLog1!=null&&wpHandleLog2!=null&&wpHandleLog2.getUpdateTime().compareTo(wpHandleLog1.getUpdateTime())<0&&StringUtils.isNotEmpty(wpHandleLog1.getNextDepartment1())
                        &&!wpHandleLog1.getNextDepartment1().equals(detailCon.getDeptLevel2())){
                    wpidsNew.add(recoverCountWpid);
                }
            }
        }

        if (wpidsNew.size()>0){
            wpInfoCountWpids.removeAll(wpidsNew);
        }

        if(detailCon.getVisitBeginTime()==null || detailCon.getVisitEndTime()==null){
            //流转工单编号集合
            detailCon.setWpIdsByFlowTime(wpInfoCountWpids);
        }

        List<WpInfoDetail> wpInfoDetails;
        if(detailCon.getVisitBeginTime()!=null && detailCon.getVisitEndTime()!=null){
            wpInfoDetails = wpInfoDetailMapper.selectWpidsByVisitDeptLevel2(detailCon);
        }else{
            wpInfoDetails = wpInfoDetailMapper.selectVisitByFlowTime(detailCon);
        }

        List<WpInfoDetail> details = new ArrayList<>();
        for (WpInfoDetail wpInfoDetail : wpInfoDetails) {
            String wpid = wpInfoDetail.getWpid();

            WpInfoDetail detail = wpInfoDetailMapper.getWpInfoDetailByWpid(wpid);
            if ("流转".equals(detail.getEndState())) {
                detail.setEndState("是");
            } else {
                detail.setEndState("否");
            }
            if ("1".equals(detail.getRecoverState())) {
                detail.setRecoverState("是");
            } else {
                detail.setRecoverState("否");
            }
            //话后满意度
            if (StringUtils.isNotEmpty(detail.getSendSatis())){
                if (detail.getSendSatis().equals("1")){
                    detail.setSendSatis("满意");
                }else if (detail.getSendSatis().equals("2")){
                    detail.setSendSatis("一般");
                }else if (detail.getSendSatis().equals("3")){
                    detail.setSendSatis("不满意");
                }
            }

            if ("1".equals(detail.getBackState())) {
                detail.setBackState("是");
            } else {
                detail.setBackState("否");
            }

            if (StringUtils.isNotEmpty(detail.getCode())) {
                SysUser sysUser = sysUserMapper.selectUserByCode(detail.getCode());
                if (sysUser != null) {
                    detail.setNickName(sysUser.getNickName());
                }
            }
            String class1 = detail.getClass1();
            String class2 = detail.getClass2();
            String class3 = detail.getClass3();
            String class4 = detail.getClass4();

            String district = detail.getDistrict();
            //区域
            if (StringUtils.isNotEmpty(district)){
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(district));
                detail.setDistrictName(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class1)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class1));
                detail.setClass1Name(sysCode.getNodename());
            }

            if (StringUtils.isNotEmpty(class2)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class2));
                detail.setClass2Name(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class3)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class3));
                detail.setClass3Name(sysCode.getNodename());
            }
            if (StringUtils.isNotEmpty(class4)) {
                SysCode sysCode = sysCodeMapper.selectSysCodeByAutoId(Long.valueOf(class4));
                detail.setClass4Name(sysCode.getNodename());
            }
            //工单是否回访过
            if ("1".equals(detail.getVisitState())) {
                WpVisitInfo wpVisitInfo = wpVisitInfoMapper.selectWpVisitInfoByWpid(detail.getWpid());
                if (StringUtils.isNotEmpty(wpInfoDetail.getIssatisfied())) {
                    detail.setIssatisfied(wpInfoDetail.getIssatisfied());
                } else {
                    detail.setIssatisfied(wpVisitInfo.getIssatisfied());
                }
                SysUser sysUser = sysUserMapper.selectUserByCode(wpVisitInfo.getVisitWorkNo());
                detail.setVisitCode(sysUser.getNickName());
                detail.setVisitResult(wpVisitInfo.getVisitResult());
                detail.setIssatisfiedReason(wpVisitInfo.getIssatisfiedReason());
            }
            if (StringUtils.isNotEmpty(detail.getDeptLevel2())) {

                String deptLevel2 = detail.getDeptLevel2();
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(deptLevel2));
                detail.setMainUnitName(sysDept.getDeptName());

                WpHandleLog log = new WpHandleLog();
                log.setNextState("承办单位处理");
                log.setWpid(detail.getWpid());
                wpHandleLogMapper.selectWpHandleLogList(log).stream()
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .ifPresent(handleLog -> {
                            //流转时间
                            detail.setEndStateTime(handleLog.getUpdateTime());
                            //流转截止时间
                            log.setNextState("工单回访");
                            wpHandleLogMapper.selectWpHandleLogList(log).stream()
                                    .max(Comparator.comparing(WpHandleLog::getUpdateTime)).ifPresent(logCon -> {
                                if (logCon.getUpdateTime().compareTo(handleLog.getUpdateTime()) > 0) {
                                    detail.setCompletionDate(logCon.getUpdateTime());
                                }
                            });

                        });
                //承办单位处理内容
                log.setLastState("承办单位处理");
                log.setNextState(null);
                wpHandleLogMapper.selectWpHandleLogList(log).stream()
                        .max(Comparator.comparing(WpHandleLog::getUpdateTime))
                        .ifPresent(handleLog -> {
                            //承办单位处理内容
                            detail.setMessage(handleLog.getMessage());
                            //是否解决
                            detail.setSolved(handleLog.getSolved());
                        });
            }
            details.add(detail);

        }

        return details;
    }

    /**
     * 满意率
     *
     * @return
     */
    public String getSatisRate(int visitSize, int satisSize, int kindSize) {

        if (visitSize==0){
            return "100.00";
        }
        //(满意度*1+一般数*0.6+  （不满意*0）)/总回访数*30
        double v = ((double) satisSize * 100 + (double) kindSize * 60) / (double) visitSize;
        //返回结果保留两位小数
        return String.format("%.2f", v );


    }
}
